const express = require('express')
const router = express.Router()
const mysql = require('../util/mysql')
// const JWT = require('../util/jwt')

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('ok')
})

// 用户注册
router.post('/apply', async (req, res, next) => {
  const promisePool = mysql.sql()
  const { name, password } = req.body
  const info = await promisePool.query('select name from user where name=?', [name])
  if (info[0].length > 0) {
    res.send({ code: 0 })
  } else {
    const token = Math.random() * 10000
    await promisePool.query('insert into user(name,password,token) value(?,?,?)', [name, password, token])
    res.send({ code: 1 })
  }
})

// 用户登录
router.post('/enter', async (req, res, next) => {
  const promisePool = mysql.sql()
  const { name, password } = req.body
  const info = await promisePool.query('select name,password,token from user where name=? and password = ?', [name, password])
  if (info[0].length > 0) {
    // 因为通过数据库查询出来的数据不是普通对象，所以需要把其中需要数据单独传出
    // const token = JWT.generate({
    //   username: info[0].name
    // }, '1d')
    const token = info[0][0].token
    res.send({ status: 1, msg: token })
  } else {
    res.send({ status: 0 })
  }
})

module.exports = router
